package com.example.springbootfastjson2;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: springboot-fastjson2
 * @description: controller
 * @author: XianJin.Lu
 * @create: 2021-09-03 09:26
 **/
@Controller
@RequestMapping("/test")
public class TestController {

    /**
     * 在这里进行转换
     *
     * @param json 假设json为请求参数
     */

    /*json数据可以用map接受 也可以用实体类接收*/
    @ResponseBody
    @RequestMapping(value = "/transJson", method = RequestMethod.POST)
    public String transJson(@RequestBody String json) {
        System.out.println("原始数据==========" + json);


     String s=   "{cmdSn:22, result: 1, resultDesc:4, resultData:[{ devAddr:'设备通信地址', devPort:'设备端口', devId:设备唯一标识,devType:设备类型,devPos:设备名称, doorNum:11, areaName:所属区域},{ devAddr:设备通信地址22, devPort:设备端口22, devId:设备唯一标识22,devType:设备类型22,devPos:设备名称22,doorNum:2, areaName:所属区域2}] }";

        Map<String, Object> params = JSON.parseObject(json, new HashMap<String, Object>().getClass());
        String studentList = params.get("studentList").toString();
        JSONArray objects = JSON.parseArray(studentList);

        objects.getJSONObject(0).get("id");

        //使用getJSONObject直接获取 JSONObject对象
        JSONObject jsonObject1 = objects.getJSONObject(1);
        Object o = objects.get(1);

        //里面都是object对象  转成字符串  再转成JSONObject对象
        for (Object object : objects) {
            System.out.println(object);

            //实体类转换成json对象
            JSONObject.toJSONString(object);
            JSONObject jsonObject = JSON.parseObject(object.toString());
            System.out.println(jsonObject.get("id"));
        }


        // 转化为teacher实体类  对于不存在的成员属性,会封装为null
        Teacher teacher = JSON.parseObject(json, Teacher.class);
        System.out.println("转换为teacher实体类==========" + teacher.toString());
        // 对teacher实体类中的studentList进行转换
        return "ok";


    }
}
